/*
 * @Author: luojianfeng
 * @Date: 2022-12-14 11:10:38
 * @LastEditTime: 2023-05-10 10:48:30
 * @LastEditors: luojianfeng
 * @Description:
 */
import path from 'path'
import { ConfigEnv, loadEnv, UserConfig } from 'vite'
import Vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx' // 配置vue使用jsx

// import generateSitemap from 'vite-ssg-sitemap'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import AutoImport from 'unplugin-auto-import/vite'
import { VitePWA } from 'vite-plugin-pwa'
import { viteMockServe } from 'vite-plugin-mock'
// import VueI18n from '@intlify/vite-plugin-vue-i18n'
import Inspect from 'vite-plugin-inspect'
import Unocss from 'unocss/vite'
export default ({ command, mode }: ConfigEnv): UserConfig => {
  const { VITE_DROP_CONSOLE, VITE_PORT, VITE_OUTPUT_DIR, ...t } = loadEnv(
    mode,
    process.cwd()
  )
  console.log(t)
  return {
    base: './',
    resolve: {
      alias: {
        '~/': `${path.resolve(__dirname, 'src')}/`,
        '@/': `${path.resolve(__dirname, 'src')}/`
      }
    },
    // esbuild: {
    //   // 使用 esbuild 压缩 剔除 console.log
    //   pure: VITE_DROP_CONSOLE ? ['console.log', 'debugger'] : []
    //   // minify: true, // minify: true, 等于 minify: 'esbuild',
    // },
    build: {
      // 设置最终构建的浏览器兼容目标
      target: 'es2015',
      minify: 'esbuild',
      // 构建后是否生成 source map 文件(用于线上报错代码报错映射对应代码)
      sourcemap: false,
      cssTarget: 'chrome80',
      // 指定输出路径（相对于 项目根目录)
      outDir: VITE_OUTPUT_DIR,
      // 只有 minify 为 terser 的时候, 本配置项才能起作用
      // terserOptions: {
      //   compress: {
      //     // 防止 Infinity 被压缩成 1/0，这可能会导致 Chrome 上的性能问题
      //     keep_infinity: true,
      //     // 打包是否自动删除 console
      //     drop_console: VITE_DROP_CONSOLE,
      //   },
      // },
      // 启用/禁用 gzip 压缩大小报告
      // 压缩大型输出文件可能会很慢，因此禁用该功能可能会提高大型项目的构建性能
      reportCompressedSize: true,
      // chunk 大小警告的限制（以 kbs 为单位）
      chunkSizeWarningLimit: 2000
    },

    css: {
      preprocessorOptions: {
        scss: {
          modifyVars: {},
          javascriptEnabled: true,
          // 注入全局 scss 变量
          additionalData: `@use "~/assets/styles/element/index.scss" as *;`
        }
      },
      postcss: {
        plugins: [
          {
            postcssPlugin: 'internal:charset-removal',
            AtRule: {
              charset: (atRule) => {
                if (atRule.name === 'charset') {
                  atRule.remove()
                }
              }
            }
          }
        ]
      }
    },
    server: {
      host: true,
      port: +VITE_PORT,
      proxy: {
        // '/api': {
        //   target: 'http://172.18.1.125:8889/',
        //   changeOrigin: true
        //   // rewrite: (path) => path.replace(/^\/api/, '')
        // }
        '/api1': {
          target: 'http://172.18.3.35:8080/',
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api1/, '')
        }
      }
    },
    plugins: [
      Vue({
        include: [/\.vue$/],
        reactivityTransform: true
      }),
      vueJsx(),
      viteMockServe({
        // https://github.com/vbenjs/vite-plugin-mock
        mockPath: 'mock',
        localEnabled: command === 'serve'
      }),

      // https://github.com/antfu/unplugin-auto-import
      AutoImport({
        include: [
          /\.[tj]sx?$/, // .ts, .tsx, .js, .jsx
          /\.vue$/,
          /\.vue\?vue/, // .vue
          /\.md$/ // .md
        ],
        imports: [
          'vue',
          'vue-router',
          // 'vue-i18n',
          'vue/macros',
          '@vueuse/head',
          '@vueuse/core'
        ],
        resolvers: [ElementPlusResolver({ importStyle: 'sass' })],
        dts: 'src/types/auto-imports.d.ts',
        dirs: ['./src/composables', './src/store', './src/request/**'], // js自动加载
        vueTemplate: true,
        eslintrc: {
          enabled: false, // 一旦生成配置文件之后，最好把enable关掉，即改成false
          filepath: './.eslintrc-auto-import.json', // Default `./.eslintrc-auto-import.json`
          globalsPropValue: true // Default `true`, (true | false | 'readonly' | 'readable' | 'writable' | 'writeable')
        }
      }),

      // https://github.com/antfu/unplugin-vue-components
      Components({
        dirs: ['src/components/'], // 组件自动加载
        // allow auto load markdown components under `./src/components/`
        extensions: ['vue'],
        resolvers: [ElementPlusResolver({ importStyle: 'sass' })], //{ importStyle: 'sass' }
        // allow auto import and register components used in markdown
        include: [/\.vue$/, /\.vue\?vue/],
        dts: 'src/types/components.d.ts'
      }),
      // https://github.com/antfu/unocss
      // see unocss.config.ts for config
      Unocss(),

      // https://github.com/antfu/vite-plugin-pwa
      VitePWA({
        registerType: 'autoUpdate',
        includeAssets: ['favicon.svg', 'safari-pinned-tab.svg'],
        manifest: {
          name: 'CyberNoteBook',
          short_name: 'CyberNoteBook',
          theme_color: '#ffffff',
          icons: [
            {
              src: '/pwa-192x192.png',
              sizes: '192x192',
              type: 'image/png'
            },
            {
              src: '/pwa-512x512.png',
              sizes: '512x512',
              type: 'image/png'
            },
            {
              src: '/pwa-512x512.png',
              sizes: '512x512',
              type: 'image/png',
              purpose: 'any maskable'
            }
          ]
        }
      }),

      // https://github.com/intlify/bundle-tools/tree/main/packages/vite-plugin-vue-i18n
      // VueI18n({
      //   runtimeOnly: true,
      //   compositionOnly: true,
      //   include: [path.resolve(__dirname, 'locales/**')],
      // }),

      // https://github.com/antfu/vite-plugin-inspect
      // Visit http://localhost:3333/__inspect/ to see the inspector
      Inspect()
    ],

    // https://github.com/vitest-dev/vitest
    test: {
      include: ['test/**/*.test.ts'],
      environment: 'jsdom',
      deps: {
        inline: ['@vue', '@vueuse', 'vue-demi']
      }
    }
  }
}
